<?php  
import ('miho.yate.plugin.*');
/**
* Yat Another Template Engine
*/
class Yate
{
  protected $_vars=array();
  public function __set($name,$value){
    $this->_vars[$name] = $value;
  }
  
  public function __get($name){
    return isset($this->_vars[$name]) ? $this->_vars[$name] : null;
  }
  
  public function clear(){
    $this->_vars = array();
  }
  /**
   * Helper functions
   *
   * @var array
   */
  protected $_helpers=array();
  protected $_heplersCache = array();
  
  public function useHelper($name){
    import('miho.view.heplers.'.$name.'Hepler');
  }
  
  public function __call($name,$args){
    $name = ucfirst($name);
    
    // Getting helper from cache
    if(isset($this->_heplersCache[$name])){
      $hepler = $this->_heplersCache[$name];
      return $call_user_func_array(
          array($helper,$name),
          $args
        );
    }
    
    foreach($this->_helpers as $helper){
      if(method_exists($helper,$name)){
        return $call_user_func_array(
          array($helper,$name),
          $args
        );
      }
    }
    throw new Exception('method '.$name.' not found!');
  }
  
  protected $_layout;
  public function setLayout($value){
    $this->_layout = $value;
  }
  
  /**
   * Helper classes.
   *
   * @var array
   */
  protected $_plugins=array();
  public function plugin($name){
    if(!isset($this->_plugins[$name])){
      throw new Exception('Plugin '.$name.' not found');
    }
    
    return $this->_plugins[$name];
  }
  
  public function registerPlugin(){
    
  }
  
  public function __construct(){
    $this->_plugins['placeholder'] = new PlaceholderPlugin();
  }
  
  public function render($file,$vars=null){
    $content = $this->renderPartial($file,$vars==null ? $this->_vars : $vars);
    return $this->renderPartial($this->_layout,array('content'=>$content));
  }
  
  public function renderPartial($partial='layout',$params=array()){
    foreach ($params as $key => $value) {
     $$key = $value; 
    }
    if(!file_exists($partial.'.phtml')){
      throw new Exception('File not found');
    }
    ob_start();
    include($partial.'.phtml');
    return ob_get_clean();
  }
  
}


?>